import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpServicesProvider } from "../../providers/http-services/http-services";
import { ConfigProvider } from "../../providers/config/config";
import { UtilsProvider } from "../../providers/utils/utils";
import { ValidateProvider } from "../../providers/validate/validate";
import { CommonProvider } from "../../providers/common/common";
import { UrlProvider } from "../../providers/url/url";
import { WechatProvider } from "../../providers/wechat/wechat";
import { StorageProvider } from "../../providers/storage/storage";

@IonicPage({
    segment: 'task/detail/:id',
    defaultHistory: ['HomePage', 'TaskPage']
})
@Component({
    selector: 'page-post-detail',
    templateUrl: 'post-detail.html',
})
export class PostDetailPage {
    @ViewChild('share') share;
    amoy_id: number;
    token: string;
    data = {
        user_info: [],
        top_info: [],
        amoy_detail: [],
        comment_list: [],
        apply_list: [],
        type: '',
        total_apply: [],
        mission_progress: []
    };
    is_owner: boolean = false;
    see_pay_info = [];
    apply_status = 0;
    //信息是否被收藏
    collected: boolean = false;
    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public httpService: HttpServicesProvider,
        public config: ConfigProvider,
        public util: UtilsProvider,
        public validate: ValidateProvider,
        public common: CommonProvider,
        public url: UrlProvider,
        public wechat: WechatProvider,
        public storage: StorageProvider,
    ) {
        // if (!this.validate.checkLogin()) {       
        //     this.navCtrl.push('LoginPage');
        // }
    }

    //判断用户是否登录
    ionViewCanEnter(): boolean {
        return this.validate.checkLogin();
    }
    ionViewWillEnter() {
        this.amoy_id = this.navParams.get('id');
        this.token = this.config.getToken();
        this.getData();
    }

    /**
     * 页面加载获取数据
     * */
    getData() {
        let loading = this.util.loading();
        let userInfo = JSON.parse(this.storage.get('userInfo'));
        loading.show();
        this.httpService.requestPostData('/task_info/mission_detail', {
            token: this.token,
            amoy_id: this.amoy_id
        }, response => {
            loading.close();
            //清除分享数据
            this.storage.remove('shareData');

            if (response.error === 200) {
                this.data['user_info'] = response['data']['user_info'];
                this.data['top_info'] = response['data']['top_info'];
                this.data['amoy_detail'] = response['data']['amoy_detail'];
                this.data['comment_list'] = response['data']['comment_list'];
                this.data['apply_list'] = response['data']['apply_list'];
                this.data['type'] = response['data']['type'];
                this.data['total_apply'] = response['data']['total_apply'];
                this.data['mission_progress'] = response['data']['mission_progress'];
                this.is_owner = response['data']['is_owner'];
                this.see_pay_info = response['data']['see_pay_info'];
                this.apply_status = response['data']['apply_status'];
                this.collected = response['data']['has_collect'];
                this.wechat.getWxConfig(() => {
                    this.wechat.wxShareMoments({ shareNumber: 2, shareTitle: '', amoyId: this.amoy_id, userId: userInfo.user_id });
                    this.wechat.wxShareFriend({ shareNumber: 2, shareTitle: '', amoyId: this.amoy_id, userId: userInfo.user_id });
                });
            }
        })
    }

    /**
     * 页面跳转
     * */
    pageRedirect(page, data = {}) {
        this.navCtrl.push(page, data).then(success => {
            if (success !== true) {//页面需要登录后跳转
                this.navCtrl.push('LoginPage', data);
            }
        })
    }

    /**
     * 任务报名
     * */

    signUp() {
        this.util.presentConfirm('您确定要报名参加当前任务吗？', () => {
            this.httpService.requestPostData('/task_info/task_sign', {
                token: this.token,
                amoy_id: this.amoy_id,
                userIds: location.search
            }, response => {
                if (response.error === 200) {
                    this.util.presentAlert(response.message);
                    this.getData();
                } else if (response.error == 401) {
                    this.util.presentConfirm('您无法调用高级用户权限，请完善注册信息', () => {
                        this.navCtrl.push('RegisterPage');
                    })
                } else {
                    this.util.presentAlert(response.message);
                }
            })
        });
    }

    /**
     * 点赞
     * */
    collect(amoy_id) {
        this.common.collect(amoy_id, (response) => {
            if (response.code == 200) {
                this.getData();
            }
        });
    }

    /**
     * 付费查看
     * */
    paySee() {
        this.httpService.requestPostData('/user_info/check_level', {
            token: this.config.getToken()
        }, (response) => {
            if (response['error'] != 200 || response['reg_step'] != 2) {
                this.util.presentConfirm('您无权使用此功能，请完善注册资料；现在去完善？', () => {
                    this.navCtrl.push('RegisterPage');
                });
            } else {
                this.util.presentConfirm('当前内容为付费查看内容，您需要支付' + this.see_pay_info['see_pay_price'] + '元', () => {
                    let postData = {
                        amoy_id: this.amoy_id,
                        token: this.token,
                        see_pay_price: this.see_pay_info['see_pay_price']
                    };
                    this.httpService.requestPostData('/task_info/pay_see_handle', postData, (response) => {
                        if (response['error'] == 200) {
                            this.util.presentAlert('付费成功');
                            this.getData();
                        } else if (response['error'] == 400) {
                            this.util.presentConfirm('当前账户余额不足，现在去充值？', () => {
                                // this.storage.set('backPage',JSON.stringify({page: 'InformationDetailPage', params: {amoy_id: this.amoy_id}}));
                                this.common.setBackPage('InformationDetailPage', { id: this.amoy_id });
                                this.navCtrl.push('MoneyRechargePage');
                            })
                        }
                    })
                }, () => {

                });
            }
        });
    }

    /**
     * 微信分享
     * */
    shareResult(title = '快来做佣丁，餐饮任务悬赏平台（淘鲜生餐饮圈）') {
        //分享到朋友圈
        let userInfo = JSON.parse(this.storage.get('userInfo'));
        this.wechat.wxShareMoments({ shareNumber: 2, amoyId: this.amoy_id, shareTitle: title, userId: userInfo.user_id }, () => {
            let apiUrl = "/task_info/insert_share";
            this.httpService.requestPostData(apiUrl, {
                token: this.config.getToken(),
                amoy_id: this.amoy_id
            }, () => {
                this.getData();
            });
        });

        //分享到朋友
        this.wechat.wxShareFriend({ shareNumber: 2, amoyId: this.amoy_id, shareTitle: title, userId: userInfo.user_id }, () => {
            let apiUrl = "/task_info/insert_share";
            this.httpService.requestPostData(apiUrl, {
                token: this.config.getToken(),
                amoy_id: this.amoy_id
            }, () => {
                this.getData();
            });
        });
    }



}
